package com.backwaveweibo.bww.config.shiro;

import com.backwaveweibo.bww.config.JWTToken;
import com.backwaveweibo.bww.utils.JwtTokenUtil;
import io.jsonwebtoken.Claims;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashSet;
import java.util.Set;


public class JwtRealm extends AuthorizingRealm {

    private Logger logger = LoggerFactory.getLogger(JwtRealm.class);


    /**
     * 限定这个 Realm 只处理我们自定义的 JwtToken
     */
    @Override
    public boolean supports(AuthenticationToken token) {

        logger.info("JwtToken supports(AuthenticationToken token) ==> " + String.valueOf(token instanceof JWTToken));
        return token instanceof JWTToken;

    }

    /**
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        logger.info("————身份认证方法————");
        String token = (String) authenticationToken.getCredentials();
        logger.info("token=========>>" + token);

        return new SimpleAuthenticationInfo(token, token, "jwtRealm");
    }

    /**
     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        logger.info("————权限认证————");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        SimpleAccount simpleAccount = new SimpleAccount();
        String role = "null";
        String token = String.valueOf(principals);
        logger.info(token);
        if (token.startsWith("Basic")) {
            return info;
        }

        Claims claims = JwtTokenUtil.parseJWT(token);
        Claims username1 = claims.setSubject("username");
        role = claims.get("role", String.class);
        logger.info("用户名:"+String.valueOf(username1));
        logger.info(role);


        //获得该用户角色
        Set<String> roleSet = new HashSet<>();
        roleSet.add(role);
        //设置该用户拥有的角色和权限
        info.setRoles(roleSet);

        return info;
    }




}
